<template>
  <div class="user-management">
    <h2>用户管理</h2>
    
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input 
            v-model="searchForm.email" 
            placeholder="请输入邮箱" 
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="enabled"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <div class="table-section">
      <el-table 
        :data="userList" 
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(scope.row)"
            />
            <span :class="['status-text', scope.row.status]">
              {{ scope.row.status === 'enabled' ? '启用' : '禁用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.role === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" v-model="dialogVisible" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" style="width: 100%;">
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)

// 编辑对话框
const dialogVisible = ref(false)
const editForm = reactive({
  id: '',
  username: '',
  email: '',
  role: 'user'
})

// 表单验证规则
const editRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 编辑表单引用
const editFormRef = ref(null)

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // 实际项目中应该调用后端API
    const response = await new Promise(resolve => {
      setTimeout(() => {
        // 模拟数据
        const mockData = Array.from({ length: 35 }, (_, index) => ({
          id: index + 1,
          username: `user${index + 1}`,
          email: `user${index + 1}@example.com`,
          role: index % 10 === 0 ? 'admin' : 'user',
          status: index % 5 === 0 ? 'disabled' : 'enabled',
          createTime: `2023-0${(index % 9) + 1}-${String(index % 28 + 1).padStart(2, '0')} 10:00:00`
        }))
        
        // 根据搜索条件过滤
        let filteredData = mockData.filter(user => {
          return (
            (searchForm.username ? user.username.includes(searchForm.username) : true) &&
            (searchForm.email ? user.email.includes(searchForm.email) : true) &&
            (searchForm.status ? user.status === searchForm.status : true)
          )
        })
        
        // 分页处理
        const start = (pagination.currentPage - 1) * pagination.pageSize
        const end = start + pagination.pageSize
        const pagedData = filteredData.slice(start, end)
        
        resolve({
          data: pagedData,
          total: filteredData.length
        })
      }, 500)
    })
    
    userList.value = response.data
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.email = ''
  searchForm.status = ''
  pagination.currentPage = 1
  fetchUserList()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUserList()
}

// 编辑用户
const handleEdit = (row) => {
  editForm.id = row.id
  editForm.username = row.username
  editForm.email = row.email
  editForm.role = row.role
  dialogVisible.value = true
}

// 提交编辑
const submitEdit = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟更新用户信息
      const index = userList.value.findIndex(user => user.id === editForm.id)
      if (index !== -1) {
        userList.value[index].email = editForm.email
        userList.value[index].role = editForm.role
      }
      ElMessage.success('更新成功')
      dialogVisible.value = false
    }
  })
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.username} 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    const index = userList.value.findIndex(user => user.id === row.id)
    if (index !== -1) {
      userList.value.splice(index, 1)
      pagination.total--
    }
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 状态变更处理
const handleStatusChange = (row) => {
  // 模拟状态变更API调用
  ElMessage.success(`用户 ${row.username} 状态已更新为${row.status === 'enabled' ? '启用' : '禁用'}`)
}

// 初始化加载数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form .el-form-item {
  margin-right: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}

.status-text {
  margin-left: 8px;
}

.status-text.enabled {
  color: #67c23a;
}

.status-text.disabled {
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>